import static org.junit.Assert.assertEquals;

import java.util.concurrent.TimeUnit;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;

import com.google.common.base.Function;

public class SeleniumBase {

	protected static WebDriver driver;

	@BeforeClass
	public static void setUp() throws Exception {
		driver = new FirefoxDriver();
		driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
	}

	@AfterClass
	public static void tearDown() throws Exception {
		driver.quit();
	}
	
	@After
	public void clear() {
		driver.manage().deleteAllCookies();
	}

	protected void open(String url) {
		driver.get(url);
	}

	protected void click(By identifier) {
		driver.findElement(identifier).click();
	}

	protected void assertElementContainsText(By identifier, String expected) {
		WebElement element = driver.findElement(identifier);
		assertEquals(expected, element.getText());
	}
	
	protected void select(By selectBoxIdentifier, String option) {
		WebElement e = driver.findElement(selectBoxIdentifier);
		new Select(e).selectByValue(option);
	}
	
	protected WebElement insertText(By identifier, String text) {
		WebElement element = driver.findElement(identifier);
		element.sendKeys(text);
		
		return element;
	}
	
	protected void waitForElement(final By identifier) {
		WebDriverWait wait = new WebDriverWait(driver, 10);
		
		wait.until(new Function<WebDriver, WebElement>() {
			@Override
			public WebElement apply(WebDriver d) {
				return d.findElement(identifier);
			}
		});
	}

	protected boolean isElementPresent(By by) {
		try {
			driver.findElement(by);
			return true;
		} catch (NoSuchElementException e) {
			return false;
		}
	}

}